let xmldoc = require('xmldoc');

/*
[reference]:
https://github.com/nfarina/xmldoc
[install]:
npm install buffer stream xmldoc
[example]:
const seq = ["n1", "n2", "n3", "n4"]
const s = "<some><head>this is header</head><body><n3 att='123'><n3-1>abc</n3-1></n3><n1>aaa</n1><n2>bbb</n2></body></some>";
const r = xmlReorder(s, "body", seq);
 */
let m = function(xmlStr, rootNodeName, orderedArray, compressed=true) {
    let document = new xmldoc.XmlDocument(xmlStr);
    let rootNode = undefined;
    if (rootNodeName === '.') {
        rootNode = document;
    } else {
        rootNode = document.descendantWithPath(rootNodeName);
    }
    if (rootNode === undefined) { return xmlStr; }
    // orderArray.sort((obj1, obj2) => {
    //     if (obj1.seq > obj2.seq) return 1;
    //     if (obj1.seq < obj2.seq) return -1;
    //     return 0;
    // });
    const childMap = {};
    rootNode.children.forEach(child => {
      if (childMap.hasOwnProperty(child.name)) { // 若有重复节点，比如两个n1，则必须都保留
        childMap[child.name].push(child);
      } else {
        childMap[child.name] = [child];
      }
    });
    rootNode.children = [];
    orderedArray.forEach(name => {
        if (childMap.hasOwnProperty(name)) {
            childMap[name].forEach(child => {
              rootNode.children.push(child);
            });
        }
    });
    return document.toString({compressed:compressed});
    // return document.toString({compressed:true})
};

module.exports = m;